package com.fzq.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fzq.dao.mapper.RbacUserMapper;
import com.fzq.dao.po.RbacUser;
import com.fzq.util.RedisMapper;
import com.fzq.util.ResponseResult;
import com.fzq.util.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证成功后的处理器
 */
@Component
public class SimpleAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource  //操作redis的类
    private RedisMapper redisMapper;

    @Resource
    private RbacUserMapper rbacUserMapper;

    /**
     * 代码走到这个方法中，说明认证成功了
     * @param request
     * @param response
     * @param authentication
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException {

        // 1. 从认证信息中获取用户详情（Spring Security 的 User 对象）
        User user = (User) authentication.getPrincipal();

        // 2. 生成 Token（通常为 JWT）
        String token = TokenUtil.getToken(user.getUsername());

        // 3. 获取用户权限并转为逗号分隔字符串（例如 "user:read,user:write"）
        Collection<GrantedAuthority> permsItem = user.getAuthorities();
        String authoritys = StringUtils.join(permsItem, ",");

        // 4. 将 Token 和权限存入 Redis（设置过期时间与 Token 一致）
        redisMapper.setKey(user.getUsername() + ":login:token", token, TokenUtil.TIMEOUT, TokenUtil.TIMEUNIT);
        redisMapper.setKey(user.getUsername() + ":author", authoritys, TokenUtil.TIMEOUT, TokenUtil.TIMEUNIT);

        // 5. 构建返回给前端的 JSON 数据
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);

        // 6. 查询业务用户表获取额外信息（如真实姓名、头像等）
        RbacUser rbacUser = rbacUserMapper.selectByUsername(user.getUsername());
        map.put("username", rbacUser.getUsername());

        // 7. 封装统一响应对象
        ResponseResult<Object> responseResult = new ResponseResult<>(200, "登录成功", map);

        // 8. 序列化 JSON 并返回
        ObjectMapper objectMapper = new ObjectMapper();
        response.setContentType("application/json;charset=UTF-8");
        String json = objectMapper.writeValueAsString(responseResult);
        PrintWriter printWriter = response.getWriter();
        printWriter.print(json);
        printWriter.flush();
        printWriter.close();
    }
}
